//
//  ViewDataController.m
//  FlowingData
//
//  Created by NIMESH DESAI on 10/10/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ViewDataController.h"

@implementation ViewDataController

#pragma mark -
#pragma mark loadData and parseData methods

-(void)_loadData
{
	loadData = YES;
	NSURL* url = [NSURL URLWithString:urlString];
	NSURLRequest* request = [NSURLRequest requestWithURL:url
											 cachePolicy:NSURLRequestUseProtocolCachePolicy
											 timeoutInterval:10.0];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	if(connection)
	{
		responseData = [[NSMutableData data] retain];
		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
		[spinner startAnimating];
	}
	NSLog(@"connection =%@", connection);
}

-(void)_parseData
{
	NSLog(@"_parseData!");
	if(xml)
		[xml release];
	xml = [[NSXMLParser alloc] initWithData:responseData];
	//NSLog(@"xml = %@", xml);
	if(!array)
		array = [[NSMutableArray alloc] init];
	[array removeAllObjects];
	[xml setDelegate:self];
	[xml setShouldProcessNamespaces:NO];
	[xml setShouldReportNamespacePrefixes:NO];
	[xml setShouldResolveExternalEntities:NO];
	[xml parse];
}

#pragma mark -
#pragma mark XML DELEGATE METHODS

-(void)parserDidStartDocument:(NSXMLParser *)parser
{
	NSLog(@"parser did start document");
}

-(void)parserDidEndDocument:(NSXMLParser *)parser
{
	NSLog(@"parserDidEndDocument");
	//NSLog(@"array=%@",array);
	NSMutableString *string = [[NSMutableString alloc] init];
	for (NSMutableDictionary *dict in array)
	{
		NSString *s = [dict objectForKey:@"s"];
		NSString *p = [dict objectForKey:@"p"];
		NSString *o = [dict objectForKey:@"o"];
		NSString *t = [dict objectForKey:@"t"];
		NSDate *date = [NSDate dateWithTimeIntervalSince1970:[t integerValue]];
		NSDateFormatter *df = [[NSDateFormatter alloc] init];
		[df setDateFormat:@"MM/dd h:mm a"];		
		[string appendFormat:@"%@ %@ %@ %@\n",s,p,o,[df stringFromDate:date]];
		[df release];
	}
	[string release];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
	NSLog(@"didStartElement");
	if([elementName isEqual:@"triple"])
		[array addObject:attributeDict];
}

#pragma mark -
#pragma mark NSURLConnection METHODS

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse *)response;
	NSLog(@"did Receive Response, response = %@", httpResponse);
	//NSLog(@"status code = %d", [httpResponse statusCode]);
	//NSLog(@"headers = %@", [httpResponse allHeaderFields]);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	//NSLog(@"didReceiveData - data=%@",data);
	NSString *string = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
	//NSLog(@"didReceiveData - data to string = %@",string);
	if(responseData)
		[responseData appendData:data];
	[string release];	
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[spinner stopAnimating];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
	[connection release];
	[responseData release];
	//NSLog(@"didFailWithError error= %@",error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	//NSLog(@"connectionDidFinishLoading");
	[spinner stopAnimating];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
	[self _parseData]; 
	[connection release]; 
	[responseData release];
}

#pragma mark -
#pragma mark buttonClicked METHOD

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

#pragma mark -
#pragma mark RELOAD METHOD

-(IBAction)reload
{
	[self _loadData];
}

#pragma mark -
#pragma mark viewDidLoad METHOD

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
	urlString = @"http://www.ist.rit.edu/~acjvks/rmail/get_recent_triples.php";
	spinner.hidesWhenStopped = YES;
	//[self _loadData];
	
	//add edit button
	self.navigationItem.rightBarButtonItem = self.editButtonItem;
	//add load button
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
											 initWithTitle:@"Load"
											 style:UIBarButtonItemStylePlain
											  target:self action:@selector(_loadData)] autorelease];
	[self _loadData];
    [super viewDidLoad];
}

#pragma mark -
#pragma mark Table VIEW METHODS

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
	 return 1;
 } 
 
 // Customize the number of rows in the table view.
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
	 return 100;
 } 
 
 // Customize the appearance of table view cells.
 - (UITableViewCell *)tableView:(UITableView *)table_View cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ 
	static NSString *CellIdentifier = @"Cell";
 
	UITableViewCell *cell = [table_View dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}
	
	if( loadData == YES )
	{
		NSUInteger row = [indexPath row];
		NSString *s = [[array objectAtIndex:indexPath.row] objectForKey:@"s"];
		NSString *p = [[array objectAtIndex:row] objectForKey:@"p"];
		NSString *o = [[array objectAtIndex:row] objectForKey:@"o"];
		NSString *t = [[array objectAtIndex:row] objectForKey:@"t"];
		NSDate *date = [NSDate dateWithTimeIntervalSince1970:[t integerValue]];
		NSDateFormatter *df = [[NSDateFormatter alloc] init];
		[df setDateFormat:@"MM/dd h:mm a"];
		NSString* temp = [[NSString alloc] initWithFormat:@" %@ %@ %@ \n %@", s, p, o, [df stringFromDate:date]];
		cell.textLabel.font = [UIFont italicSystemFontOfSize:11];
		cell.textLabel.text = temp;
		[temp release];
		[df release];
	}
	// Set up the cell...
 
	return cell;
 }
 
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	// Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
 }

 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
	// Return NO if you do not want the specified item to be editable.
	return YES;
 }

 // Override to support editing the table view.
 - (void)tableView:(UITableView *)table_View commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{ 
	if (editingStyle == UITableViewCellEditingStyleDelete)
	{
		// Delete the row from the data source
		[table_View deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
	}   
	else 
		if (editingStyle == UITableViewCellEditingStyleInsert)
		{
			// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
		}   
 }

 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}

 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
	// Return NO if you do not want the item to be re-orderable.
	return YES;
 }

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning 
{
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use
}

- (void)viewDidUnload
{
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc 
{
	[tableView release];
	[spinner release];
	[responseData release];
	[urlString release];
    [super dealloc];
}

@end
